package com.cnooc.zyfx.service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.SQLException;

import org.joda.time.DateTime;

import com.github.thorqin.toolkit.Application;
import com.github.thorqin.toolkit.annotation.Service;
import com.github.thorqin.toolkit.db.DBService;
import com.github.thorqin.toolkit.db.DBService.DBField;
import com.github.thorqin.toolkit.db.DBService.DBSession;

@Service("report")
public class ReportService {
	@Service("db")
	private DBService db;
	
	@Service("application")
	Application app;
	
	public static class ReportURLEntity {
		@DBField("id")
		public String id;
		@DBField("report_url")
		public String reportURL;
		@DBField("report_url_time")
		public DateTime urlTime;
		@DBField("account")
		public String sapUser;
		@DBField("password")
		public String sapPassword;
	}
	
	public String getReportUrl(String userId) throws Exception {
		try (DBSession session = db.getSession(false)) {
			ReportURLEntity entity = session.queryFirst(
					app.readScript("sql/queryReportURL.sql"), ReportURLEntity.class, userId);
			if (entity.reportURL == null || (DateTime.now().getMillis() - 
					entity.urlTime.getMillis() > 1000 * 60 * 10) ) {
				// 获取新的 url
				String newUrl = obtainReportURL(entity.sapUser, entity.sapPassword);
				// 然后存入数据库
				session.execute("update tb_sap_user set report_url = ?, report_url_time = now() where id = (?)::uuid"
						, newUrl, entity.id);
				session.commit();
				return newUrl;
			} else {
				return entity.reportURL;
			}
		}
	}
	
	public static String obtainReportURL(String account, String password) throws Exception {
		HttpURLConnection.setFollowRedirects(false);
		try {
			HttpURLConnection conn = (HttpURLConnection)new URL("http://10.63.4.51/AdminTools/custom.jsp?username1=" 
					+ URLEncoder.encode(account, "utf-8") 
					+ "&password1=" + 
					URLEncoder.encode(password, "utf-8") 
					).openConnection();
			int code = conn.getResponseCode();
			if (code == 302) {
				String location = conn.getHeaderField("location");
				conn.disconnect();
				return location.substring(0, location.length() - 1);
			} else {
				conn.disconnect();
				return null;
			}
		} finally {
			HttpURLConnection.setFollowRedirects(true);
		}
	}
}
